




#ifdef GL_ES
precision mediump float;
#endif

varying vec2 v_texCoord;

uniform sampler2D CC_Texture0;
uniform sampler2D u_normalMap;

uniform vec4 u_diffuseM;
uniform vec4 u_ambientM;
uniform vec4 u_diffuseL;
uniform vec4 u_ambientL;
uniform vec2 u_contentSize;
uniform vec4 u_lightPosInLocalSpace;
uniform float u_kBump;
void main() {
    vec4 diffuseML=u_diffuseM*u_diffuseL;
    vec4 ambientML=u_ambientM*u_ambientL;
    //
    vec4 texColor=texture2D(CC_Texture0, v_texCoord);
    vec3 normal=texture2D(u_normalMap, v_texCoord).rgb;
    normal=normal*2.0-1.0;//make it to range [-1,1]. see: http://user.qzone.qq.com/350479720/blog/1399375155
    //because the normal map generated by 'Nvidia Texture Tools for photoshop' use down-toward Y, so we should reverse it
    //see: http://user.qzone.qq.com/350479720/blog/1403447890
    normal.y=-normal.y;
    //extra bump
    if(u_kBump!=1.0){
        //if the vertex.z mult kBump, then the normal.z should div kBump and re-normalize
        normal=vec3(normal.x,normal.y,normal.z/u_kBump);
        normal=normalize(normal);
    }
    vec4 curPixelPosInLocalSpace=vec4(v_texCoord.x*u_contentSize.x,
                                      (1.0-v_texCoord.y)*u_contentSize.y,0.0,1.0);//because we do not know the z value of the pixel, so we let it be zero
    vec4 lightDir=normalize(curPixelPosInLocalSpace-u_lightPosInLocalSpace);
    //ambient
    vec4 ambient=ambientML;
    //diffuse
    vec3 posToLight=-lightDir.xyz;
    float normDotPosToLight=max(0.0,dot(normal,posToLight));
    vec4 diffuse=vec4(normDotPosToLight*vec3(diffuseML),1.0);
    //
    gl_FragColor=texColor*vec4(vec3(diffuse+ambient),diffuse.a);
    


}

